package com.nerve.secondhandcar.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ko.commons.config.PropertyConfigurer;
import org.ko.core.web.BaseController;
import org.ko.core.web.Result;
import org.ko.core.websupport.Reply;
import org.ko.core.websupport.log.Log;
import org.ko.core.websupport.log.impl.LogUitls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.nerve.secondhandcar.common.C;
import com.nerve.secondhandcar.common.bean.ImageResult;
import com.nerve.secondhandcar.controller.model.CarCategoryModel;
import com.nerve.secondhandcar.controller.model.CarModel;
import com.nerve.secondhandcar.controller.model.PictureModel;
import com.nerve.secondhandcar.domain.Car;
import com.nerve.secondhandcar.domain.Picture;
import com.nerve.secondhandcar.service.CarService;
import com.nerve.secondhandcar.service.PictureService;

/**
 * 平台中的汽车对象Controller
 * @author 集成显卡
 * @version 2014-10-09 10:51:08
 */
@Controller
@RequestMapping("/car")
public class CarController extends BaseController{

	public static final String BASIC = "basic";
	public static final String PICTURE = "picture";
	public static final String CONFIGURE = "configure";
	public static final String REPORT = "report";
	
	@Autowired
	private CarService service;
	@Autowired
	private PictureService picService;
	
	@Override
	protected String getTemplatePath() {
		return "car/car/";
	}
	
	/**
	 * 访问汽车的编辑页面，有以下类型（model.template)：
	 * basic		默认，打开基本信息页面
	 * picture		打开图片页面
	 * confiture	打开配置页面
	 * report 		打开报告页面
	 * 
	 * @method name: add
	 * @return type: String
	 *	@return
	 */
	@RequestMapping(value="add")
	@RequiresPermissions("carManage:add")
	public String add(HttpServletRequest req, CarModel model,ModelMap map) throws Exception{
		
		if(!StringUtils.hasText(model.getTemplate())){
			model.setTemplate(BASIC);
		}
		if(BASIC.equals(model.getTemplate()))
			map.addAttribute("categoryList", service.categoryList());
		
		//如果id不大于0，则是新建汽车，那么页面直接锁定到BASIC
		if(model.getId() <= 0){
			if(!BASIC.equals(model.getTemplate()))
				map.addAttribute(C.ERROR, "请先创建汽车信息");
			model.setTemplate(BASIC);
			
			Car car = new Car();
			car.setId(0l);
			map.addAttribute(ENTITY, car);
			map.addAttribute("template", model.getTemplate());
			return view(model.getTemplate());
		}
		
		service.add(model);
		map.addAttribute(ENTITY, model.getCar());
		map.addAttribute("template", model.getTemplate());
		map.addAttribute("id", model.getId());
		
		return view(model.getTemplate());
	}
	
	/**
	 * 查看实体
	 * @param req
	 * @param model
	 * @param viewMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="view")
	public String view(HttpServletRequest req, CarModel model, ModelMap viewMap)
		throws Exception {
		service.view(model);
		
		viewMap.addAttribute(ENTITY, model.getCar());
		return view(VIEW);
	}
	
	/**
	 * 判断指定的汽车是否存在
	 * @param req
	 * @param model
	 * @return
	 */
	@RequestMapping(value="exist")
	@ResponseBody
	public Reply exist(HttpServletRequest req, CarModel model){
		Reply re = new Reply();
		try {
			service.isExist(model);
			re.setMessage(model.getId());
		} catch (Exception e) {
			re.error(e);
		}
		return re;
	}
	
	@Log(message="保存汽车基本信息", category="Car")
	@RequestMapping(value="saveBasic", method=RequestMethod.POST)
	@RequiresPermissions("carManage:saveBasic")
	public String saveBasic(HttpServletRequest request, HttpServletResponse response, CarModel model, ModelMap map){
		try {
			service.basicDo(model);
			long id = model.getCar().getId();
			LogUitls.putLog(id >0?"编辑":"新建");
			
			//保留到原页面
			if(model.getToView()==0){
				return redirect("add.do?template="+BASIC+"&id="+id);
			}else{
				return redirect("add.do?template="+PICTURE+"&id="+id);
			}
		} catch (Exception e) {
			return doWithError(map, model, BASIC, e);
		}
	}
	
	@Log(message="保存汽车配置信息", category="Car")
	@RequestMapping(value="saveConfigure", method=RequestMethod.POST)
	@RequiresPermissions("carManage:saveConfigure")
	public String saveConfigure(HttpServletRequest request, HttpServletResponse response, CarModel model, ModelMap map){
		try {
			service.configureDo(model);
			long id = model.getCar().getId();
			LogUitls.putLog("编辑");
			
			//保留到原页面
			if(model.getToView()==0){
				return redirect("add.do?template="+CONFIGURE+"&id="+id);
			}else{
				return redirect("add.do?template="+REPORT+"&id="+id);
			}
		} catch (Exception e) {
			return doWithError(map, model, CONFIGURE, e);
		}
	}

	@Log(message="保存汽车评测报告", category="Car")
	@RequestMapping(value="saveReport", method=RequestMethod.POST)
	@RequiresPermissions("carManage:saveReport")
	public String saveReport(HttpServletRequest request, HttpServletResponse response, CarModel model, ModelMap map){
		try {
			service.reportDo(model);
			long id = model.getCar().getId();
			LogUitls.putLog("编辑");
			
			//保留到原页面
			if(model.getToView()==0){
				return redirect("add.do?template="+REPORT+"&id="+id);
			}else{
				return redirect("add.do?template="+BASIC+"&id="+id);
			}
		} catch (Exception e) {
			return doWithError(map, model, REPORT, e);
		}
	}
	
	private String doWithError(ModelMap map, CarModel model,String template, Exception e){
		System.err.println("出错啦！");
		e.printStackTrace();
		LogUitls.error(e);
		
		map.addAttribute(C.ERROR, e.getMessage());
		map.addAttribute(ENTITY, model.getCar());
		map.addAttribute("template", template);
		if(BASIC.equals(template)){
			map.addAttribute("categoryList", service.categoryList());
		}
		return view(template);
	}
	
	@Log(message="Ajax创建了汽车")
	@RequestMapping(value="createAjax")
	@ResponseBody
	public Reply createAjax(HttpServletRequest req, CarModel model)
			throws Exception {
		Reply re = new Reply();
		try {
			service.create(model);
			re.setMessage("创建成功");
		} catch (Exception e) {
			re.error(e);
			e.printStackTrace();
		}
		return re;
	}
	
	@RequiresPermissions("carManage:delete")
	@Log(message="删除了汽车[id={0}]", params={"id"}, category="Car")
	@RequestMapping(value="delete")
	@ResponseBody
	public Reply delete(HttpServletRequest req, CarModel model)
			throws Exception {
		Reply re = new Reply();
		try {
			service.delete(model);
			re.setMessage("删除成功");
		} catch (Exception e) {
			re.error(e);
			e.printStackTrace();
		}
		return re;
	}
	
	@RequiresPermissions("carManage:delete")
	@Log(message="批量删除汽车信息,id={0}",params={"ids"}, category="Car")
	@RequestMapping(value="delete",method = RequestMethod.POST)
	public @ResponseBody Result delete(
			HttpServletRequest request,
			HttpServletResponse response,
			ModelMap model,
			@RequestParam(value = "ids", required = true)Long ids[]){
		Result result = new Result();
		try {
			service.delete(ids);
			result.setMessage("操作成功");
		} catch (Exception e) {
			result.error(e);
			LogUitls.error(e);
		}
		return result;
	}
	
	@Log(message="刷新了汽车[id={0}]", params={"id"}, category="Car")
	@RequestMapping(value="refresh")
	@ResponseBody
	public Reply refresh(HttpServletRequest req, CarModel model)
			throws Exception {
		Reply re = new Reply();
		try {
			service.refresh(model);
			re.setMessage("删除成功");
		} catch (Exception e) {
			re.error(e);
			e.printStackTrace();
		}
		return re;
	}
	
	@RequiresPermissions("carManage:list")
	@RequestMapping(value="list")
	public String list(HttpServletRequest req, CarModel model, ModelMap map) throws Exception{
		service.list(model);
		map.addAttribute(PAGINATION, model);
		map.addAttribute("keyword", model.getKeyword());
		return view(LIST);
	}
	
	@RequiresPermissions("carManage:specialPrice")
	@Log(message="修改汽车特价信息,id={0}",params={"id"}, category="Car")
	@RequestMapping(value="specialPrice",method = RequestMethod.POST)
	public @ResponseBody Result specialPrice(
			HttpServletRequest request,
			HttpServletResponse response,
			CarModel model
			){
		Result result = new Result();
		try {
			int re = service.specialPrice(model);
			result.setMessage(re+"");
		} catch (Exception e) {
			result.error(e);
			LogUitls.error(e);
		}
		return result;
	}
	
	@Log(message="修改汽车销售信息,id={0}",params={"id"}, category="Car")
	@RequestMapping(value="status",method = RequestMethod.POST)
	public @ResponseBody Result changeStatus(
			HttpServletRequest request,
			HttpServletResponse response,
			CarModel model
			){
		Result result = new Result();
		try {
			int re = service.changeStatus(model);
			result.setMessage(re+"");
		} catch (Exception e) {
			result.error(e);
			LogUitls.error(e);
		}
		return result;
	}
	
	/*
	 * ================================================================
	 * Start 汽车图片
	 * ================================================================
	 */
	/**
	 * 查看汽车图片
	 */
	@RequestMapping(value="picture")
	public String pictures(HttpServletRequest req, @RequestParam(value="id", required=true)Long id, ModelMap map)
		throws Exception {
		map.addAttribute(ENTITY, service.get(id));
		map.addAttribute("template", PICTURE);
		return view(PICTURE);
	}
	
	/**
	 * 上传图片
	 * @method name: upload
	 * @return type: String
	 *	@param req
	 *	@param file
	 *	@param carId
	 *	@return
	 */
	@RequiresPermissions("carManage:picture.upload")
	@Log(message="上传图片", category="Picture")
	@RequestMapping(value="picture/upload",method=RequestMethod.POST)
	public String upload(
			HttpServletRequest req, 
			@RequestParam(value="upload_file",required=false)MultipartFile file, 
			@RequestParam(value="id", required=true)Long carId,
			RedirectAttributes redirectA
			) throws Exception{
		
		/*
		 * 设置参数
		 */
		ImageResult imgR = new ImageResult();
		imgR.setCreateThumb(true);
		imgR.setDeleteOrigin(false);
		imgR.setHeight(PropertyConfigurer.getInt(C.UPLOAD_HEIGHT_NORMAL, 450));
		imgR.setWidth(PropertyConfigurer.getInt(C.UPLOAD_WIDTH_NORMAL, 600));
		imgR.setHeightThumb(PropertyConfigurer.getInt(C.UPLOAD_HEIGHT_THUMB, 80));
		imgR.setWidthThumb(PropertyConfigurer.getInt(C.UPLOAD_WIDTH_THUMB, 100));
		
		/*
		 * 设置Picture的属性
		 */
		Picture pic = new Picture();
		pic.setAppId(carId);
		pic.setCategory("CAR");
		
		try {
			picService.dealUploadImage(req, file, imgR, pic);
			
			LogUitls.putLog(file.getOriginalFilename());
		} catch (Exception e) {
			LogUitls.error(e);
			
			redirectA.addFlashAttribute("error", e.getMessage());
			e.printStackTrace();
		}
		
		return redirect("/car/add.do?id="+carId+"&template="+PICTURE);
	}
	/**
	 * 通过ajax上传的图片
	 * @method name: upload
	 * @return type: Result
	 *	@param req
	 *	@param file
	 *	@param carId
	 *	@return
	 *	@throws Exception
	 */
	@RequiresPermissions("carManage:picture.upload")
	@Log(message="上传图片", category="Picture")
	@RequestMapping(value="picture/uploadAjax",method=RequestMethod.POST)
	public @ResponseBody Result upload(
			HttpServletRequest req, 
			@RequestParam(value="upload_file",required=false)MultipartFile file, 
			@RequestParam(value="id", required=true)Long carId
			) throws Exception{
		
		Result re = new Result();
		/*
		 * 设置参数
		 */
		ImageResult imgR = new ImageResult();
		imgR.setCreateThumb(true);
		imgR.setDeleteOrigin(false);
		imgR.setHeight(PropertyConfigurer.getInt(C.UPLOAD_HEIGHT_NORMAL, 450));
		imgR.setWidth(PropertyConfigurer.getInt(C.UPLOAD_WIDTH_NORMAL, 600));
		imgR.setHeightThumb(PropertyConfigurer.getInt(C.UPLOAD_HEIGHT_THUMB, 80));
		imgR.setWidthThumb(PropertyConfigurer.getInt(C.UPLOAD_WIDTH_THUMB, 100));
		
		/*
		 * 设置Picture的属性
		 */
		Picture pic = new Picture();
		pic.setAppId(carId);
		pic.setCategory("CAR");
		
		try {
			picService.dealUploadImage(req, file, imgR, pic);
			
			LogUitls.putLog(file.getOriginalFilename());
		} catch (Exception e) {
			LogUitls.error(e);
			
			re.error(e);
			e.printStackTrace();
		}
		return re;
	}
	
	/**
	 * 
	 * @method name: deletePicture
	 * @return type: Result
	 *	@param req
	 *	@param id
	 *	@return
	 */
	@RequiresPermissions("carManage:picture.delete")
	@Log(message="删除汽车图片，id={0}", params={"id"}, category="Picture")
	@RequestMapping(value="picture/delete")
	@ResponseBody
	public Result deletePicture(HttpServletRequest req, PictureModel model){
		Result re = new Result();
		try {
			picService.delete(model, req);
		} catch (Exception e) {
			LogUitls.error(e);
			re.error(e);
		}
		return re;
	}
	
	@RequiresPermissions("carManage:picture.sort")
	@Log(message="重新排序汽车图片，id={0}", params={"id"}, category="Picture")
	@RequestMapping(value="picture/sort")
	public @ResponseBody Result pictureSort(PictureModel model){
		Result re = new Result();
		try {
			picService.sort(model);
		} catch (Exception e) {
			LogUitls.error(e);
			re.error(e);
		}
		return re;
	}
	/*
	 * ================================================================
	 * END 汽车图片
	 * ================================================================
	 */
	
	/*
	 * ================================================================
	 * Start 汽车类型
	 * ================================================================
	 */
	@RequiresPermissions("carManage:category.list")
	@RequestMapping(value="category/list")
	public String categoryList(HttpServletRequest req, ModelMap map, CarCategoryModel model	) throws Exception{
		service.categoryList(model);
		map.addAttribute(PAGINATION, model);
		return view("category_list");
	}
	
	@RequiresPermissions("carManage:category.edit")
	@Log(message="编辑汽车类型", category="Car")
	@RequestMapping(value="category/edit", method=RequestMethod.POST)
	public @ResponseBody Result categoryEdit(HttpServletRequest req, CarCategoryModel model)throws Exception{
		Result re = new Result();
		try {
			service.categorySave(model);
			
			LogUitls.putLog("操作成功，id="+model.getCategory().getId());
		} catch (Exception e) {
			LogUitls.error(e);
			
			re.error(e);
		}
		
		return re;
	}
	
	@RequiresPermissions("carManage:category.delete")
	@Log(message="批量删除汽车类型,id={0}",params={"ids"}, category="Car")
	@RequestMapping(value="category/delete",method = RequestMethod.POST)
	public @ResponseBody Result categoryDelete(
			HttpServletRequest request,
			HttpServletResponse response,
			CarCategoryModel model){
		Result result = new Result();
		try {
			service.categoryDelete(model);
			result.setMessage("操作成功");
		} catch (Exception e) {
			result.error(e);
			LogUitls.error(e);
		}
		return result;
	}
	/*
	 * ================================================================
	 * END 汽车类型
	 * ================================================================
	 */
	
}